package com.zmn.oms.admin.controller.work.modify;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.base.common.data.common.dio.company.CompanyDIO;
import com.zmn.base.common.data.common.dio.company.CompanyTypeDIO;
import com.zmn.base.common.data.common.dro.company.CompanyFinanceDRO;
import com.zmn.base.common.data.common.dro.tags.TagsDRO;
import com.zmn.base.common.data.dubbo.interfaces.company.CompanyListRemoteService;
import com.zmn.base.plat.engine.common.constant.CompanyConsts;
import com.zmn.common.constant.FicoConsts;
import com.zmn.common.dto2.Option;
import com.zmn.common.dto2.OptionData;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.admin.controller.work.WorkBaseController;
import com.zmn.oms.business.interfaces.attachment.AttachmentBService;
import com.zmn.oms.common.annotation.PageRequestCas;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dro.orderpay.OrderPayResultDRO;
import com.zmn.oms.common.dto.BankAccountDTO;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.vo.KVDict;
import com.zmn.oms.model.dto.work.masterwork.CompleteDTO;
import com.zmn.oms.model.dto.work.modify.OrderCompleteReviewDTO;
import com.zmn.oms.model.dto.work.modify.must.ZsOrderPayDTO;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.attachment.AttachmentDetailGroupVO;
import com.zmn.oms.model.vo.attachment.WorkAttachmentVO;
import com.zmn.oms.model.vo.work.OperatePermissionVO;
import com.zmn.oms.model.vo.work.OrderServiceCompleteReviewVO;
import com.zmn.oms.services.interfaces.invoice.OrderInvoiceService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.orderpay.AccountPayBService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.zmn.business.interfaces.orderpay.OrderPayChannelBService;
import com.zmn.oms.zmn.business.interfaces.statistics.StatOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkAmountBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import com.zmn.oms.zmn.business.interfaces.work.masterwork.ZsMasterWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.orderpay.OrderPayResultBService;
import com.zmn.oms.zmn.business.interfaces.work.orderpay.ZsOrderPayBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.masterwork.ZsNormalMasterWorkBService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.pay.gateway.common.model.dro.PayGatewayDRO;
//import com.zmn.plat.common.dto.orderconfig.serviceaudit.OrderServiceAuditReasonDIO;
//import com.zmn.plat.common.dto.orderconfig.serviceaudit.OrderServiceAuditReasonDRO;
//import com.zmn.plat.dubbo.interfaces.orderconfig.serviceaudit.OrderServiceAuditReasonListRemoteService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：工单完成
 *
 * @author lujia
 * @date 2018-12-18 22:19:56
 */
@Controller
@RequestMapping("/work/modify")
public class WorkCompleteController extends WorkBaseController {

	@Autowired
	ZsOrderPayBService zsOrderPayBService;
	@Autowired
	ZsNormalMasterWorkBService zsNormalMasterWorkBService;
	@Autowired
	ZsOrderWorkOperatePermissionBService orderWorkOperatePermissionBService;
	@Autowired
	OrderInvoiceService orderInvoiceService;
	@Autowired
	ZsMasterWorkBService zsMasterWorkBService;
	@Autowired
	OrderExtendService orderExtendService;
	@Autowired
	OrderServiceItemService orderServiceItemService;
	@Autowired
	WorkFlowContextBService workFlowContextBService;
	@Autowired
	OrderPayChannelBService orderPayChannelBService;
	@Resource
	AttachmentBService attachmentBService;
	@Autowired
	ZsOrderWorkAmountBService zsOrderWorkAmountBService;
	@Autowired
	OrderPayResultBService orderPayResultBService;
	@Resource
	private StatOrderBService statOrderBService;

	@Autowired
	AccountPayBService accountPayBService;
	@Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
	private CompanyListRemoteService companyListRemoteService;
//	@Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
//	private OrderServiceAuditReasonListRemoteService orderServiceAuditReasonListRemoteService;

	/**
	 * 服务完成
	 */
	@RequestMapping(value = "/serviceCompleteReview")
	public ModelAndView serviceComplete(Long orderId, Long workId, Long operatorId) {
		ModelAndView mv = new ModelAndView("work/modify/servicecompletereview");
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);

		OrderServiceCompleteReviewVO orderServiceCompleteReviewVO = BeanMapper.map(orderWork, OrderServiceCompleteReviewVO.class);

		// 若上月派单工单，下月5号往后也不可标示
		Date distributeTime = orderWork.getDistributeTime();
		boolean supportOperate = DateUtil.isCurMonthOrBetween1to5Day(distributeTime);
		orderServiceCompleteReviewVO.setIsOperate(supportOperate);
		// 收费项目
		List<OrderServiceItem> orderServiceItems = orderServiceItemService.listByOrderId(orderWork.getOrderId());
		orderServiceCompleteReviewVO.setOrderServiceItemList(orderServiceItems);
		// 订单内部价
		orderServiceCompleteReviewVO.setInternalTotalPrice(orderServiceItems.stream().mapToInt(OrderServiceItem::getInternalTotalPrice).sum());
		// 审核失败原因
		List<TagsDRO> tagsDROS = baseCodeService.listBaseCodeMap(GlobalConsts.PLAT_MARK_ZMN, 1068, orderWork.getBizType(), null);
		if (CollectionUtil.isNotNullOrEmpty(tagsDROS)) {
			List<KVDict> collect = tagsDROS.stream().map(dro -> KVDict.builder().value(dro.getThreeTypeId())
					.text(dro.getName()).ext1(dro.getDesc()).build()).collect(Collectors.toList());
			orderServiceCompleteReviewVO.setAuditReason(collect);
		}
		mv.addObject("reviewVO", orderServiceCompleteReviewVO);
		mv.addObject("operatorId", operatorId);
		return mv;
	}

	/**
	 * 保存服务完成审核结果
	 */
	@RequestMapping(value = "save/serviceCompleteReview")
	@ResponseBody
	public ResultDTO saveServiceComplete(@RequestBody OrderCompleteReviewDTO orderCompleteReviewDTO) {

		OperatePermissionVO operatePermission = orderWorkOperatePermissionBService.getOperatePermission(orderCompleteReviewDTO.getOrderId(),
				orderCompleteReviewDTO.getWorkId(), OrderConsts.ORDER_OP_TYPE_SERVICE_COMPLETE_REVIEW);
		if (!operatePermission.getCanOperate()) {
			return ResultDTO.fail(operatePermission.getMsg());
		}
		try {
			zsMasterWorkBService.saveCompleteReview(orderCompleteReviewDTO);
		}catch (OmsBaseException omsException){
			logger.info("服务完成审核失败：{}", JSON.toJSONString(omsException.getMessage()));
			return ResultDTO.fail(omsException.getMessage());
		}
		// 自动流转
		workFlowContextBService.asyncAutoFlow(orderCompleteReviewDTO.getOrderId(), orderCompleteReviewDTO.getWorkId());

		return ResultDTO.success();
	}

	/**
	 * 完成
	 */
	@RequestMapping(value = "/complete")
	@PageRequestCas(type = OrderConsts.ORDER_OP_TYPE_COMPLETE)
	public ModelAndView complete(Long orderId, Long workId, Long operatorId) {
		ModelAndView mv = new ModelAndView("work/modify/complete");
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
		// 获取转账银行信息
		// List<Map<String, String>> list = this.checkInvoice(orderWork);
		List<BankAccountDTO> bankAccountList = this.getBankAccountList(orderWork);
		// 是否显示支付
		int showPay = (Objects.equals(orderWork.getBizType(), GlobalConsts.BIZ_TYPE_C) || ChannelConsts.CHANNEL_ID_NOSUPPORT_ACCOUNT_PAY.contains(orderWork.getChannelId()))
				&& !Objects.equals(orderWork.getPayStatus(), PayConsts.PAY_STATUS_DONE)
				&& !(Objects.equals(orderWork.getMasterAmount(), 0))
				? GlobalConsts.YES : GlobalConsts.NO;
		// 显示资金帐号支付
		//int showAccountPay = Objects.equals(orderWork.getBizType(), GlobalConsts.BIZ_TYPE_F) ? GlobalConsts.YES : GlobalConsts.NO;
		// 显示支付宝和微信支付
		int showAlipayAndWeixinpay = orderPayChannelBService.onlySupportBankTransfer(orderWork.getBizModeSource(), orderWork.getChannelId())
				? GlobalConsts.NO : GlobalConsts.YES;
		// 显示银行转账支付
		int showBanktransferPay = Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_ZMN)
				|| Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_CNHB) ? GlobalConsts.YES : GlobalConsts.NO;

		mv.addObject("showPay", showPay);
		mv.addObject("showAlipayAndWeixinpay", showAlipayAndWeixinpay);
		mv.addObject("showBanktransferPay", showBanktransferPay);
		mv.addObject("bankAccountList", bankAccountList);
		mv.addObject("orderWork", orderWork);
		mv.addObject("operatorId", operatorId);
		return mv;
	}

	/**
	 * 生成支付二维码
	 */
	@RequestMapping(value = "/complete/pay")
	@ResponseBody
	public ResultDTO findCompletePayQr(@RequestBody ZsOrderPayDTO completeDTO) throws OmsBaseException {
		OperatePermissionVO operatePermission = orderWorkOperatePermissionBService.getOperatePermission(completeDTO.getOrderId(), completeDTO.getWorkId(),
				OrderConsts.ORDER_OP_TYPE_COMPLETE, GlobalConsts.OPERATE_USER_TYPE_STAFF, super.getCurrentStaff().getStaffId().longValue());
		if (!operatePermission.getCanOperate()) {
			return ResultDTO.fail(operatePermission.getMsg());
		}

		// 操作完成次数
		Integer subCompanyCompleteCount = null;

		// 子公司银行转账，直接返回成功并提示剩余操作次数
		if (Objects.equals(completeDTO.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_BANKTRANSFER)) {
			subCompanyCompleteCount = this.getSubCompanyCompleteCount();
		}

		com.zmn.pay.gateway.common.model.dro.PayGatewayDRO payRepsDRO = zsOrderPayBService.payMasterAmount(completeDTO);
		String qrCode = payRepsDRO.getQrCode();

		Map<String, Object> result = Maps.newHashMapWithExpectedSize(2);
		result.put("qrCode", qrCode);

		// 计算剩余次数
		if(subCompanyCompleteCount != null){
			OrderWork orderWork = orderWorkService.findOrderWorkByKey(completeDTO.getOrderId(), completeDTO.getWorkId());
			Integer subCompanyRemainingCompleteCount = this.getSubCompanyRemainingCompleteCount(orderWork.getPlatWork(), subCompanyCompleteCount);
			if (subCompanyRemainingCompleteCount != null) {
				result.put("message", String.format("操作成功！剩余可操作次数：%s", subCompanyRemainingCompleteCount));
			}
		}

		return ResultDTO.success(result);
	}

	/**
	 * 直接完成
	 */
	@RequestMapping(value = "termination/complete")
	@ResponseBody
	public ResultDTO saveTerminationComplete(@Validated @RequestBody ZsOrderPayDTO payDTO) {
		try {
			// 权限验证
			OperatePermissionVO operatePermission = orderWorkOperatePermissionBService.getOperatePermission(payDTO.getOrderId(), payDTO.getWorkId(), OrderConsts.ORDER_OP_TYPE_COMPLETE,
					GlobalConsts.OPERATE_USER_TYPE_STAFF, super.getCurrentStaff().getStaffId().longValue());
			if (!operatePermission.getCanOperate()) {
				return ResultDTO.fail(operatePermission.getMsg());
			}
			OrderWork orderWork = orderWorkService.findOrderWorkByKey(payDTO.getOrderId(), payDTO.getWorkId());

			if (ChannelConsts.CHANNEL_ID_NOSUPPORT_ACCOUNT_PAY.contains(orderWork.getChannelId())
					&& NumberUtil.isNotNullOrZero(orderWork.getMasterAmount())) {
				return ResultDTO.fail("天猫订单，不能存在工程师收款");
			}

			// 新单F单完成，完成支付
			if (Objects.equals(orderWork.getType(),OrderConsts.ORDER_TYPE_NEW)
					&& Objects.equals(com.zmn.consts.GlobalConsts.BIZ_TYPE_F, orderWork.getBizType())
					&& !ChannelConsts.CHANNEL_ID_NOSUPPORT_ACCOUNT_PAY.contains(orderWork.getChannelId())
					&& !Objects.equals(PayConsts.PAY_STATUS_DONE, orderWork.getPayStatus())) {
				ZsOrderPayDTO zsOrderPayDTO = new ZsOrderPayDTO();
				zsOrderPayDTO.setPayChannelId(accountPayBService.getPayChannelIdByOrderId(orderWork.getOrderId()));
				zsOrderPayDTO.setPayType(PayConsts.PAY_TYPE_INTO);
				zsOrderPayDTO.setTransferTime(new Date());
				zsOrderPayDTO.setSyncFlag(com.zmn.consts.GlobalConsts.YES);
				zsOrderPayDTO.setOrderId(orderWork.getOrderId());
				zsOrderPayDTO.setWorkId(orderWork.getWorkId());
				zsOrderPayDTO.setPlat(orderWork.getPlatWork());
				zsOrderPayDTO.setOperatorPlat(orderWork.getPlatWork());
				zsOrderPayDTO.setOperator(com.zmn.common.constant.GlobalConsts.getOperatorTypeName(com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
				zsOrderPayDTO.setOperatorId(Long.valueOf(com.zmn.consts.GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
				zsOrderPayDTO.setOperatorType(com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
				zsOrderPayDTO.setAccountType(FicoConsts.ACC_FACTORY);
				// 同步支付
				PayGatewayDRO payGatewayDRO = zsOrderPayBService.payMasterAmount(zsOrderPayDTO);
				// 更新支付结果
				OrderPayResultDRO orderPayResultDRO = orderPayResultBService.convertOrderPayResult(payGatewayDRO.getStatus());
				orderPayResultDRO.setAmountType(OrderPayConsts.ORDER_PAY_MASTER);
				zsOrderWorkAmountBService.updateMasterAmountPayResult(orderPayResultDRO);
			}

			// 操作完成次数
			Integer subCompanyCompleteCount = this.getSubCompanyCompleteCount();

			// 完成
			CompleteDTO completeDTO = BeanMapper.map(payDTO, CompleteDTO.class);
			completeDTO.setStatus(OrderStatusConsts.WORK_STATUS_COMPLETE);
			completeDTO.setResultStatus(OrderStatusConsts.WORK_RESULT_DOING);
			zsNormalMasterWorkBService.completeOrder(completeDTO);

			workFlowContextBService.asyncAutoFlow(payDTO.getOrderId(), payDTO.getWorkId());

			Map<String, Object> result = Maps.newHashMapWithExpectedSize(2);
			if (subCompanyCompleteCount != null) {
				Integer subCompanyRemainingCompleteCount = this.getSubCompanyRemainingCompleteCount(orderWork.getPlatWork(), subCompanyCompleteCount);
				if (subCompanyRemainingCompleteCount != null) {
					result.put("message", String.format("操作成功！剩余可操作次数：%s", subCompanyRemainingCompleteCount));
				}
			}

			return ResultDTO.success(result);
		} catch (Exception e) {
			return ResultDTO.fail(e.getMessage());
		}
    }

    /**
     * 完成 页面循环调用是否支付成功
     */
    @RequestMapping(value = "/save/complete")
    @ResponseBody
    public ResultDTO saveComplete(@RequestBody ZsOrderPayDTO completeDTO) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(completeDTO.getOrderId(), completeDTO.getWorkId());
        Integer masterPayStatus = orderWork.getMasterPayStatus();

        Map<String, Object> result = Maps.newHashMapWithExpectedSize(2);
		result.put("payStatus", masterPayStatus);

		// 支付完成，并且是子公司完成的，需要提示剩余次数
		if (Objects.equals(masterPayStatus, PayConsts.PAY_STATUS_DONE) && super.isBranchCompany()) {
			Integer subCompanyRemainderCompleteCount = this.getSubCompanyRemainingCompleteCount(orderWork.getPlatWork(), this.getSubCompanyCompleteCount());
			if (subCompanyRemainderCompleteCount != null) {
				result.put("message", String.format("支付成功！剩余可操作次数：%s", subCompanyRemainderCompleteCount));
			}
		}

		return ResultDTO.success(result);
    }

    /**
     * 描述: 文件上传  （现没有传oss 接口 需后续修改为 上传到oss）
     *
     * @param file      文件对象
     * @param timestamp 时间戳
     * @param elemId    元素id
     * @return com.zmn.oms.common.dto.ResultDTO
     * @author sunlife
     * @date 2019/07/17 11:51
     */
    @RequestMapping(value = "complete/uploaderImage")
    @ResponseBody
    public ResultDTO uploaderMasterImage(@RequestParam(value = "file") MultipartFile file,
                                         @RequestParam(value = "timestamp") String timestamp,
                                         @RequestParam(value = "elemId") String elemId) {

        StringBuilder path = new StringBuilder();
        path.append("/oms/order/complete/").append(elemId).append("/").append(timestamp);

        return super.uploaderImage(file, path.toString());
    }

	/**
	 * 银行信息
	 *
	 * @param orderWork
	 * @return
	 * @modifier huangchao 转账账号取值地址及逻辑变更
	 */
	private List<BankAccountDTO> getBankAccountList(OrderWork orderWork) {
		List<Integer> companyIdList = Lists.newArrayList();
		// 新机销售，笨鸟公司
		if (ProductConsts.LIST_SPECIAL_SERV_PRODUCT_GROUP.contains(orderWork.getServProductGroupId())) {
			companyIdList.add(CompanyBankAccountConsts.BN_COMPANY_ID);
		}

		// 执行子公司 = 家修匠？
		if (CollectionUtil.isNullOrEmpty(companyIdList)
				&& Objects.equals(orderWork.getCompanyId(), CompanyBankAccountConsts.ZMN_JXJ_COMPANY_ID)) {
			companyIdList.add(CompanyBankAccountConsts.ZMN_COMPANY_ID);
			companyIdList.add(CompanyBankAccountConsts.ZMN_JXJ_COMPANY_ID);
		}

		// 针对防水补漏、房屋翻新两条业务线的工单，在进行操作完成时，银行账户信息新增川南的银行账户选择
		if (CollectionUtil.isNullOrEmpty(companyIdList)
				&& (Objects.equals(orderWork.getBizLine(), BizLineConstants.C_BIZ_LINE_HOUSE_REPAIR))) {
			companyIdList.add(CompanyBankAccountConsts.CNHB_COMPANY_ID);
		}

		if (CollectionUtil.isNullOrEmpty(companyIdList) || companyIdList.contains(CompanyBankAccountConsts.CNHB_COMPANY_ID)) {
			//取：执行子公司下的信息公司 + 电器公司，两个公司的账户信息
			// 电器公司
			CompanyTypeDIO companyTypeDIO = new CompanyTypeDIO();
			companyTypeDIO.setType(CompanyConsts.COMPANY_TYPE_ELECTRIC);
			companyTypeDIO.setChildType(CompanyConsts.COMPANY_TYPE_CHILD_DEFAULT);
			// 信息公司
			CompanyTypeDIO companyTypeDIO2 = new CompanyTypeDIO();
			companyTypeDIO2.setType(CompanyConsts.COMPANY_TYPE_SERVICE);
			companyTypeDIO2.setChildType(CompanyConsts.COMPANY_TYPE_SERVICE_OCO);

			CompanyDIO baseCompanyDIO = new CompanyDIO();
			baseCompanyDIO.setSubCompanyId(orderWork.getCompanyId());
			baseCompanyDIO.setPlat(orderWork.getPlatWork());
			baseCompanyDIO.setCompanyTypeQueryList(Arrays.asList(companyTypeDIO, companyTypeDIO2));
			ResponseDTO<OptionData<Integer>> listResponseDTO = companyListRemoteService.listPageOptionByCompanyDIO(baseCompanyDIO);

			logger.info("转账公司：{}-->{}", JSON.toJSONString(baseCompanyDIO), JSON.toJSONString(listResponseDTO));

			if (Objects.nonNull(listResponseDTO.getData()) || CollectionUtil.isNotNullOrEmpty(listResponseDTO.getData().getOptions())) {
				companyIdList.addAll(listResponseDTO.getData().getOptions().stream().map(Option<Integer>::getValue).collect(Collectors.toList()));
			}
		}

		if (CollectionUtil.isNullOrEmpty(companyIdList)) {
			return Lists.newArrayList();
		}
		ResponseDTO<List<CompanyFinanceDRO>> listCompanyFinanceResDTO = companyListRemoteService.listCompanyFinanceByIds(companyIdList);
		logger.info("转账公司财务信息：{}-->{}", companyIdList, JSON.toJSONString(listCompanyFinanceResDTO));
		if (listCompanyFinanceResDTO.isSuccess() && CollectionUtil.isNotNullOrEmpty(listCompanyFinanceResDTO.getData())) {
			List<BankAccountDTO> bankAccountDTOList = listCompanyFinanceResDTO.getData().stream()
					.filter(companyFinanceDRO -> Objects.nonNull(companyFinanceDRO.getBankCardNo()))
					.map(companyFinanceDRO -> BankAccountDTO.builder()
							.companyId(companyFinanceDRO.getCompanyId())
							.companyName(companyFinanceDRO.getFullName())
							.bankName(companyFinanceDRO.getBankName())
							.bankAccount(companyFinanceDRO.getBankCardNo()).build()
					).collect(Collectors.toList());
			return bankAccountDTOList;
		}

		return Lists.newArrayList();
	}

	/**
	 * 查询操作剩余次数
	 *
	 * @param platWork
	 * @return
	 */
	private Integer getSubCompanyRemainingCompleteCount(Integer platWork, Integer subCompanyCompleteCount) {
		if (subCompanyCompleteCount == null) {
			return null;
		}
		TagsDRO oneBaseCodeMap = baseCodeService.getOneBaseCodeMap(platWork,8001, null);
		if (oneBaseCodeMap == null || oneBaseCodeMap.getTwoTypeId() == null) {
			return null;
		}
		Integer maxCompletedCount = oneBaseCodeMap.getTwoTypeId();

		// 同步延迟问题需要+1
		return Math.abs(maxCompletedCount - subCompanyCompleteCount.intValue() - 1);
	}

	/**
	 * 查询操作完成次数
	 * @return
	 */
	private Integer getSubCompanyCompleteCount() {
		if (!super.isBranchCompany()) {
			return null;
		}

		Long count = statOrderBService.countCompletedOrderByCompleteId(super.getCurrentStaff().getStaffId().longValue(),
				DateUtil.getMonthFirstDay(DateUtil.getNow()), null);
		return count.intValue();
	}

}
